﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using Traceability.Register.Application.Commonds.TraceabilityManagementCommonds;
using Traceability.Register.Domain;
using Traceability.Register.ErrorCode.Result;
using Traceability.Register.Infrastructrue;

namespace Traceability.Register.Application.CommondHandlers.TraceabilityManagementCommondHandlers
{
    /// <summary>
    /// 修改请求命令处理
    /// </summary>
    public class UpdateQRCodeRequestCommondHandler : IRequestHandler<UpdateQRCodeRequestCommond, ApiResult>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdateQRCodeRequestCommondHandler> logger;
        /// <summary>
        /// 溯源信息仓储
        /// </summary>
        private readonly IBaseRepository<Traceabilitys> baseRepository;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="baseRepository">溯源信息仓储</param>
        public UpdateQRCodeRequestCommondHandler(ILogger<UpdateQRCodeRequestCommondHandler> logger, IBaseRepository<Traceabilitys> baseRepository)
        {
            this.logger = logger;
            this.baseRepository = baseRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult> Handle(UpdateQRCodeRequestCommond request, CancellationToken cancellationToken)
        {
            try
            {
                var entity=mapper.Map<Traceabilitys>(request);
                await baseRepository.UpdateAsync(entity);
                return ApiResult.Ok("修改成功");
            }
            catch (Exception ex)
            {
                logger.LogError("修改失败" + ex.Message);
                throw;
            }
        }
    }
}
